from api import models
from rest_framework import serializers


class CreateCommentSerializer(serializers.ModelSerializer):
    create_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)

    # 根评论：news、content、reply=null、depth=0、root=null
    # 子评论：news, content, reply=回复的评论ID, depth=回复的评论深度+1,
    #   - root=回复的评论 if 回复的评论.root==null else 回复的评论.root
    # descendant_update_datetime 根评论最近的更新时间。最新的子评论时间。
    class Meta:
        model = models.Comment
        fields = ['news', 'reply', 'content', 'depth', 'create_datetime']
        read_only_fields = ['depth']
        extra_kwargs = {
            'news': {'write_only': True}
        }


class ListCommentSerializer(serializers.ModelSerializer):
    create_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    children = serializers.SerializerMethodField()

    class Meta:
        model = models.Comment
        fields = ['create_datetime', 'reply', 'content', 'children']

    def get_children(self, obj):
        # 获取当前根评论的所有子孙评论
        descendant_queryset = models.Comment.objects.filter(root=obj).order_by('id')
        descendant_dict = {}
        # 将评论添加children属性，依次写入字典
        for descendant in descendant_queryset:
            ser = CreateCommentSerializer(instance=descendant)
            row = {'children': []}
            row.update(ser.data)
            descendant_dict.update({descendant.id: row})
        # 按照评论回复关系，生成嵌套列表
        children_list = []
        for cid, item in descendant_dict.items():
            depth = item.get('depth')
            if depth == 1:
                children_list.append(item)
                continue
            reply_id = item.get('reply')
            descendant_dict.get(reply_id).get('children').append(item)
        return children_list
